package comm.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.oreilly.servlet.multipart.FileRenamePolicy;

public class PalmFileRenamePolicy implements FileRenamePolicy{
        // This method does not need to be synchronized because createNewFile()
          // is atomic and used here to mark when a file name is chosen
                
        public String originName  = "";
        
          public File rename(File f) {
           
            String name = f.getName();
            String body = null;
            String ext = null;      
            
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSS"); 
        Date currentTime = new Date();
        String dateString = formatter.format(currentTime);
        
        originName = name;
            int dot = name.lastIndexOf(".");
            if (dot != -1) {
                body = dateString;
                ext = name.substring(dot);  // includes "."
            }
            else {
              body = dateString;
              ext = "";
            }
            
           f = new File(f.getParent(), body  + ext);
           if (createNewFile(f)) {
                      return f;
                    }
              
            // Increase the count until an empty spot is found.
            // Max out at 9999 to avoid an infinite loop caused by a persistent
            // IOException, like when the destination dir becomes non-writable.
            // We don't pass the exception up because our job is just to rename,
            // and the caller will hit any IOException in normal processing.
            int count = 0;
            while (!createNewFile(f) && count < 9999) {
              count++;
              String newName = body + count + ext;
              f = new File(f.getParent(), newName);
            }
            
            System.out.println("변경된 파일 이름 : "+body);

            return f;
          }

          private boolean createNewFile(File f) {
            try {
              return f.createNewFile();
            }
            catch (IOException ignored) {
              return false;
            }
          }
}
